{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Spider-Man"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*Modeling and Simulation in Python*\n",
    "\n",
    "Copyright 2021 Allen Downey\n",
    "\n",
    "License: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# install Pint if necessary\n",
    "\n",
    "try:\n",
    "    import pint\n",
    "except ImportError:\n",
    "    !pip install pint"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# download modsim.py if necessary\n",
    "\n",
    "from os.path import basename, exists\n",
    "\n",
    "def download(url):\n",
    "    filename = basename(url)\n",
    "    if not exists(filename):\n",
    "        from urllib.request import urlretrieve\n",
    "        local, _ = urlretrieve(url, filename)\n",
    "        print('Downloaded ' + local)\n",
    "    \n",
    "download('https://github.com/AllenDowney/ModSimPy/raw/master/modsim.py')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# import functions from modsim\n",
    "\n",
    "from modsim import *"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this case study we'll develop a model of Spider-Man swinging from a springy cable of webbing attached to the top of the Empire State Building.  Initially, Spider-Man is at the top of a nearby building, as shown in this diagram.\n",
    "\n",
    "![Diagram of the initial state for the Spider-Man case\n",
    "study.](https://github.com/AllenDowney/ModSim/raw/main/figs/spiderman.png)\n",
    "\n",
    "The origin, `O⃗`, is at the base of the Empire State Building.  The vector `H⃗` represents the position where the webbing is attached to the building, relative to `O⃗`.  The vector `P⃗` is the position of Spider-Man relative to `O⃗`.  And `L⃗` is the vector from the attachment point to Spider-Man.\n",
    "\n",
    "By following the arrows from `O⃗`, along `H⃗`, and along `L⃗`, we can see that \n",
    "\n",
    "`H⃗ + L⃗ = P⃗`\n",
    "\n",
    "So we can compute `L⃗` like this:\n",
    "\n",
    "`L⃗ = P⃗ - H⃗`\n",
    "\n",
    "The goals of this case study are:\n",
    "\n",
    "1. Implement a model of this scenario to predict Spider-Man's trajectory.\n",
    "\n",
    "2. Choose the right time for Spider-Man to let go of the webbing in order to maximize the distance he travels before landing.\n",
    "\n",
    "3. Choose the best angle for Spider-Man to jump off the building, and let go of the webbing, to maximize range."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "I'll create a `Params` object to contain the quantities we'll need:\n",
    "\n",
    "1. According to [the Spider-Man Wiki](http://spiderman.wikia.com/wiki/Peter_Parker_%28Earth-616%29), Spider-Man weighs 76 kg.\n",
    "\n",
    "2. Let's assume his terminal velocity is 60 m/s.\n",
    "\n",
    "3. The length of the web is 100 m.\n",
    "\n",
    "4. The initial angle of the web is 45 degrees to the left of straight down.\n",
    "\n",
    "5. The spring constant of the web is 40 N / m when the cord is stretched, and 0 when it's compressed.\n",
    "\n",
    "Here's a `Params` object with the parameters of the system."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "params = Params(height = 381,    # m,\n",
    "                g = 9.8,         # m/s**2,\n",
    "                mass = 75,       # kg,\n",
    "                area = 1,        # m**2,\n",
    "                rho = 1.2,       # kg/m**3,\n",
    "                v_term = 60,     # m / s,\n",
    "                length = 100,          # m,\n",
    "                angle = (270 - 45),    # degree,\n",
    "                k = 40,                # N / m,\n",
    "                t_0 = 0,               # s,\n",
    "                t_end = 30,            # s\n",
    "               )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Compute the initial position"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def initial_condition(params):\n",
    "    \"\"\"Compute the initial position and velocity.\n",
    "    \n",
    "    params: Params object\n",
    "    \"\"\"\n",
    "    H⃗ = Vector(0, params.height)\n",
    "    theta = np.deg2rad(params.angle)\n",
    "    x, y = pol2cart(theta, params.length)\n",
    "    L⃗ = Vector(x, y)\n",
    "    P⃗ = H⃗ + L⃗\n",
    "    \n",
    "    return State(x=P⃗.x, y=P⃗.y, vx=0, vy=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "initial_condition(params)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now here's a version of `make_system` that takes a `Params` object as a parameter.\n",
    "\n",
    "`make_system` uses the given value of `v_term` to compute the drag coefficient `C_d`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "def make_system(params):\n",
    "    \"\"\"Makes a System object for the given conditions.\n",
    "    \n",
    "    params: Params object\n",
    "    \n",
    "    returns: System object\n",
    "    \"\"\"\n",
    "    init = initial_condition(params)\n",
    "    \n",
    "    mass, g = params.mass, params.g\n",
    "    rho, area, v_term = params.rho, params.area, params.v_term\n",
    "    C_d = 2 * mass * g / (rho * area * v_term**2)\n",
    "    \n",
    "    return System(params, init=init, C_d=C_d)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's make a `System`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "system = make_system(params)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "system.init"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Drag and spring forces\n",
    "\n",
    "Here's drag force, as we saw in Chapter 22."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "def drag_force(V⃗, system):\n",
    "    \"\"\"Compute drag force.\n",
    "    \n",
    "    V⃗: velocity Vector\n",
    "    system: `System` object\n",
    "    \n",
    "    returns: force Vector\n",
    "    \"\"\"\n",
    "    rho, C_d, area = system.rho, system.C_d, system.area\n",
    "    \n",
    "    mag = rho * vector_mag(V⃗)**2 * C_d * area / 2\n",
    "    direction = -vector_hat(V⃗)\n",
    "    f_drag = direction * mag\n",
    "    return f_drag"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "V⃗_test = Vector(10, 10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "drag_force(V⃗_test, system)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And here's the 2-D version of spring force.  We saw the 1-D version in Chapter 21."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "def spring_force(L⃗, system):\n",
    "    \"\"\"Compute drag force.\n",
    "    \n",
    "    L⃗: Vector representing the webbing\n",
    "    system: System object\n",
    "    \n",
    "    returns: force Vector\n",
    "    \"\"\"\n",
    "    extension = vector_mag(L⃗) - system.length\n",
    "    if extension < 0:\n",
    "        mag = 0\n",
    "    else:\n",
    "        mag = system.k * extension\n",
    "        \n",
    "    direction = -vector_hat(L⃗)\n",
    "    f_spring = direction * mag\n",
    "    return f_spring"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "L⃗_test = Vector(0, -system.length-1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "f_spring = spring_force(L⃗_test, system)\n",
    "f_spring"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here's the slope function, including acceleration due to gravity, drag, and the spring force of the webbing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "def slope_func(t, state, system):\n",
    "    \"\"\"Computes derivatives of the state variables.\n",
    "    \n",
    "    state: State (x, y, x velocity, y velocity)\n",
    "    t: time\n",
    "    system: System object with g, rho, C_d, area, mass\n",
    "    \n",
    "    returns: sequence (vx, vy, ax, ay)\n",
    "    \"\"\"\n",
    "    x, y, vx, vy = state\n",
    "    P⃗ = Vector(x, y)\n",
    "    V⃗ = Vector(vx, vy)\n",
    "    g, mass = system.g, system.mass\n",
    "    \n",
    "    H⃗ = Vector(0, system.height)\n",
    "    L⃗ = P⃗ - H⃗\n",
    "    \n",
    "    a_grav = Vector(0, -g)\n",
    "    a_spring = spring_force(L⃗, system) / mass\n",
    "    a_drag = drag_force(V⃗, system) / mass\n",
    "    \n",
    "    A⃗ = a_grav + a_drag + a_spring\n",
    "    \n",
    "    return V⃗.x, V⃗.y, A⃗.x, A⃗.y"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As always, let's test the slope function with the initial conditions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "slope_func(0, system.init, system)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And then run the simulation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "results, details = run_solve_ivp(system, slope_func)\n",
    "details.message"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Visualizing the results\n",
    "\n",
    "We can extract the x and y components as `Series` objects."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The simplest way to visualize the results is to plot x and y as functions of time."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_position(results):\n",
    "    results.x.plot(label='x')\n",
    "    results.y.plot(label='y')\n",
    "\n",
    "    decorate(xlabel='Time (s)',\n",
    "             ylabel='Position (m)')\n",
    "    \n",
    "plot_position(results)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can plot the velocities the same way."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_velocity(results):\n",
    "    results.vx.plot(label='vx')\n",
    "    results.vy.plot(label='vy')\n",
    "\n",
    "    decorate(xlabel='Time (s)',\n",
    "             ylabel='Velocity (m/s)')\n",
    "    \n",
    "plot_velocity(results)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Another way to visualize the results is to plot y versus x.  The result is the trajectory through the plane of motion."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_trajectory(results, label):\n",
    "    x = results.x\n",
    "    y = results.y\n",
    "    make_series(x, y).plot(label=label)\n",
    "\n",
    "    decorate(xlabel='x position (m)',\n",
    "             ylabel='y position (m)')\n",
    "    \n",
    "plot_trajectory(results, label='trajectory')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Letting go\n",
    "\n",
    "Now let's find the optimal time for Spider-Man to let go.  We have to run the simulation in two phases because the spring force changes abruptly when Spider-Man lets go, so we can't integrate through it.\n",
    "\n",
    "Here are the parameters for Phase 1, running for 9 seconds."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [],
   "source": [
    "params1 = params.set(t_end=9)\n",
    "system1 = make_system(params1)\n",
    "results1, details1 = run_solve_ivp(system1, slope_func)\n",
    "plot_trajectory(results1, label='phase 1')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The final conditions from Phase 1 are the initial conditions for Phase 2."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [],
   "source": [
    "t_0 = results1.index[-1]\n",
    "t_0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [],
   "source": [
    "init = results1.iloc[-1]\n",
    "init"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [],
   "source": [
    "t_end = t_0 + 10"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here is the `System` for Phase 2.  We can turn off the spring force by setting `k=0`, so we don't have to write a new slope function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [],
   "source": [
    "system2 = system1.set(init=init, t_0=t_0, t_end=t_end, k=0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here's an event function that stops the simulation when Spider-Man reaches the ground."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [],
   "source": [
    "def event_func(t, state, system):\n",
    "    \"\"\"Stops when y=0.\n",
    "    \n",
    "    state: State object\n",
    "    t: time\n",
    "    system: System object\n",
    "    \n",
    "    returns: height\n",
    "    \"\"\"\n",
    "    x, y, vx, vy = state\n",
    "    return y"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Run Phase 2."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [],
   "source": [
    "results2, details2 = run_solve_ivp(system2, slope_func, \n",
    "                                   events=event_func)\n",
    "details2.message"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Plot the results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [],
   "source": [
    "plot_trajectory(results1, label='phase 1')\n",
    "plot_trajectory(results2, label='phase 2')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can gather all that into a function that takes `t_release` and `V_0`, runs both phases, and returns the results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_two_phase(t_release, params):\n",
    "    \"\"\"Run both phases.\n",
    "    \n",
    "    t_release: time when Spider-Man lets go of the webbing\n",
    "    \"\"\"\n",
    "    params1 = params.set(t_end=t_release)\n",
    "    system1 = make_system(params1)\n",
    "    results1, details1 = run_solve_ivp(system1, slope_func)\n",
    "\n",
    "    t_0 = results1.index[-1]\n",
    "    t_end = t_0 + 10\n",
    "    init = results1.iloc[-1]\n",
    "\n",
    "    system2 = system1.set(init=init, t_0=t_0, t_end=t_end, k=0)\n",
    "    results2, details2 = run_solve_ivp(system2, slope_func, \n",
    "                                       events=event_func)\n",
    "\n",
    "    return pd.concat([results1, results2])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And here's a test run."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [],
   "source": [
    "t_release = 9 \n",
    "results = run_two_phase(t_release, params)\n",
    "plot_trajectory(results, 'trajectory')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [],
   "source": [
    "x_final = results.iloc[-1].x\n",
    "x_final"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Animation\n",
    "\n",
    "Here's a draw function we can use to animate the results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [],
   "source": [
    "from matplotlib.pyplot import plot\n",
    "\n",
    "xlim = results.x.min(), results.x.max()\n",
    "ylim = results.y.min(), results.y.max()\n",
    "\n",
    "def draw_func(t, state):\n",
    "    plot(state.x, state.y, 'bo')\n",
    "    decorate(xlabel='x position (m)',\n",
    "             ylabel='y position (m)',\n",
    "             xlim=xlim,\n",
    "             ylim=ylim)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [],
   "source": [
    "# animate(results, draw_func)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Maximizing range\n",
    "\n",
    "To find the best value of `t_release`, we need a function that takes possible values, runs the simulation, and returns the range."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [],
   "source": [
    "def range_func(t_release, params):\n",
    "    \"\"\"Compute the final value of x.\n",
    "    \n",
    "    t_release: time to release web\n",
    "    params: Params object\n",
    "    \"\"\"\n",
    "    results = run_two_phase(t_release, params)\n",
    "    x_final = results.iloc[-1].x\n",
    "    print(t_release, x_final)\n",
    "    return x_final"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can test it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [],
   "source": [
    "range_func(9, params)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And run it for a few values."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [],
   "source": [
    "for t_release in linrange(3, 15, 3):\n",
    "    range_func(t_release, params)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can use `maximize_scalar` to find the optimum."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [],
   "source": [
    "bounds = [6, 12]\n",
    "res = maximize_scalar(range_func, params, bounds=bounds)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, we can run the simulation with the optimal value."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [],
   "source": [
    "best_time = res.x\n",
    "results = run_two_phase(best_time, params)\n",
    "plot_trajectory(results, label='trajectory')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [],
   "source": [
    "x_final = results.iloc[-1].x\n",
    "x_final"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
